use leptos::{ev, html, prelude::*};
use thaw::TextareaResize;
use thaw_utils::{class_list, mount_style, BoxOneCallback, Model};

#[component]
pub fn ChatTextarea(
    #[prop(optional, into)] class: MaybeProp<String>,
    #[prop(optional, into)] style: MaybeProp<String>,
    #[prop(optional, into)] value: Model<String>,
    /// Check the incoming value, if it returns false, input will not be accepted.
    #[prop(optional, into)]
    allow_value: Option<BoxOneCallback<String, bool>>,
    /// Placeholder text for the input.
    #[prop(optional, into)]
    placeholder: MaybeProp<String>,
    /// Callback triggered when the input is focussed on.
    #[prop(optional, into)]
    on_focus: Option<BoxOneCallback<ev::FocusEvent>>,
    /// Callback triggered when the input is blurred.
    #[prop(optional, into)]
    on_blur: Option<BoxOneCallback<ev::FocusEvent>>,
    /// Whether the input is disabled.
    #[prop(optional, into)]
    disabled: Signal<bool>,
    /// Which direction the Textarea is allowed to be resized.
    #[prop(optional, into)]
    resize: Signal<TextareaResize>,
) -> impl IntoView {
    mount_style("textarea", include_str!("./textarea.css"));
    let value_trigger = ArcTrigger::new();
    let on_input = {
        let value_trigger = value_trigger.clone();
        move |ev| {
            let input_value = event_target_value(&ev);
            if let Some(allow_value) = allow_value.as_ref() {
                if !allow_value(input_value.clone()) {
                    value_trigger.notify();
                    return;
                }
            }
            value.set(input_value);
        }
    };

    let on_internal_focus = move |ev| {
        if let Some(on_focus) = on_focus.as_ref() {
            on_focus(ev);
        }
    };
    let on_internal_blur = move |ev| {
        if let Some(on_blur) = on_blur.as_ref() {
            on_blur(ev);
        }
    };

    let textarea_ref = NodeRef::<html::Textarea>::new();

    view! {
        <span
            style=move || style.get()
            class=class_list![
                "flex flex-col",
                "thaw-textarea",
            ("thaw-textarea--disabled", move || disabled.get()),
            move || format!("thaw-textarea--resize-{}", resize.get().as_str()),
            class
            ]
        >
            <textarea
                prop:value=move || {
                    value_trigger.track();
                    value.get()
                }

                on:input=on_input
                on:focus=on_internal_focus
                on:blur=on_internal_blur
                class="thaw-textarea__textarea"
                disabled=move || disabled.get()
                placeholder=move || placeholder.get()
                node_ref=textarea_ref
            ></textarea>
            <div class="felx justify-end">
                <label class="float-right border-none mr-[10px] mb-[4px]">{"发送(S)"}</label>
            </div>
        </span>
    }
}
